package com.example.dahua.proxy.dynamicProxy;

import com.example.dahua.proxy.staticProxy.BuyHouse;
import com.example.dahua.proxy.staticProxy.BuyHouseImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: dangwen
 * @createDate: 2021/7/3
 * 在动态代理中我们不再需要再手动的创建代理类，我们只需要编写一个动态处理器就可以了。真正的代理对象由JDK再运行时为我们动态的来创建。
 */
public class JdkProxy implements InvocationHandler {

    private Object object;
    public JdkProxy(final Object object){
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] objects) throws Throwable {
        preByHouse();
        Object invokeObject = method.invoke(object, objects);
        afterByHouse();
        return invokeObject;
    }
    public void preByHouse(){
        System.out.println("请准备好钱!");
    }
    public void afterByHouse(){
        System.out.println("请带走房产证！");
    }
    public static void main(String[] args) {
        BuyHouse buyHouse = new BuyHouseImpl();
        BuyHouse buyHouse1 = (BuyHouse) Proxy.newProxyInstance(BuyHouse.class.getClassLoader(), new Class[]{BuyHouse.class}, new JdkProxy(buyHouse));
        buyHouse1.byHouse();
    }

}
